package com.longway.common.rateLimiter;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.ehcache.CacheKit;
import com.longway.common.kit.IpKit;
 
/**
 * LimitInterceptor.
 */
public class LimitInterceptor implements Interceptor {
	
	public static final String limitedCacheName = "limitedCache";
	
    @Override
    public void intercept(Invocation inv) {
    		//访问者IP
            String ip = IpKit.getRealIp(inv.getController().getRequest());
            //请求接口路径
            String uri = inv.getController().getRequest().getRequestURI();
            //创建缓存访问时间
            String cacheKeyTime = "requesttime_"+ip;
            //创建缓存访问地址
            String cacheKeyUri =  "requesuri_"+ip;
            //判断是否加入黑名单
//            if(ip.equals(CacheKit.get(limitedCacheName, "blacklist"))){
//            	inv.getController().renderJson(Ret.fail("msg", "已加入黑名单请联系管理员解除"));
//            	return;
//            }
            //取出缓存访问时间
            Long preRequestTime = CacheKit.get(limitedCacheName, cacheKeyTime);
            //取出缓存访问地址
            String preRequestUri = CacheKit.get(limitedCacheName, cacheKeyUri);
            
            //判断这个ip是否已经调用过该接口
            if(preRequestTime != null && preRequestUri != null){
            	//判断这个ip请求是否是统一个接口并且不大于200毫秒
            	if(uri.equals(preRequestUri)&&  System.currentTimeMillis() - preRequestTime < 200){
            		//加入黑名单
            		 CacheKit.put(limitedCacheName, "blacklist", ip);
            		inv.getController().renderJson(Ret.fail("msg", "请求次数频繁，请稍后重试"));
                    return ;
            	}
            }
            //存放访问时间缓存
            CacheKit.put(limitedCacheName, cacheKeyTime, System.currentTimeMillis());
            //存放访问ip
            CacheKit.put(limitedCacheName, cacheKeyUri, uri);
        inv.invoke();
    }
     
}
